package net.tv90.appserveradmin.controller;

import cn.dev33.satoken.annotation.SaCheckRole;
import net.tv90.appserveradmin.model.Users;
import net.tv90.appserveradmin.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
@RequestMapping("/users")
public class UserController {
    @Autowired
    private UserService usersService;

    @SaCheckRole("admin")
    @GetMapping
    public String listUsers(Model model) {
        List<Users> usersList = usersService.list();
        model.addAttribute("users", usersList);
        return "users/list";
    }

    @SaCheckRole("admin")
    @GetMapping("/add")
    public String addUserForm(Model model) {
        model.addAttribute("user", new Users());
        return "users/add";
    }

    @SaCheckRole("admin")
    @PostMapping("/add")
    public String addUser(@ModelAttribute Users user) {
        usersService.save(user);
        return "redirect:/users";
    }

    @SaCheckRole("admin")
    @GetMapping("/edit/{id}")
    public String editUserForm(@PathVariable String id, Model model) {
        Users user = usersService.getById(id);
        model.addAttribute("user", user);
        return "users/edit";
    }

    @SaCheckRole("admin")
    @PostMapping("/edit")
    public String editUser(@ModelAttribute Users user) {
        usersService.updateById(user);
        return "redirect:/users";
    }

    @SaCheckRole("admin")
    @GetMapping("/delete/{id}")
    public String deleteUser(@PathVariable String id) {
        usersService.removeById(id);
        return "redirect:/users";
    }

    @SaCheckRole("admin")
    @GetMapping("/view/{id}")
    public String viewUser(@PathVariable String id, Model model) {
        Users user = usersService.getById(id);
        model.addAttribute("user", user);
        return "users/view";
    }
}